import {onMounted, reactive, ref,unref} from "vue"
import {post} from "@/utils/http"

interface UseHttpOptions {
    pageKey?: string;      // 页码参数名，默认 'page'
    pageSizeKey?: string;  // 每页条数参数名，默认 'pageSize'
    totalKey?: string;     // 总数参数名，默认 'total'
    listKey?: string;      // 列表数据参数名，默认 'list'
    filterEmptyValues?: boolean; // 是否过滤空值参数，默认 false
    customApi?: (params: any) => Promise<any>; // 自定义API函数
}

export function useHttp<T>(url:string, initialParams:any, options: UseHttpOptions = {}){
    const {
        pageKey = 'page',
        pageSizeKey = 'pageSize', 
        totalKey = 'total',
        listKey = 'list',
        filterEmptyValues = false,
        customApi
    } = options;

    const dataList=ref<T[]>([]); //用来存表格的
    const loading=ref<boolean>(false);
    const totals=ref<number>(0);
    const pageInfo=reactive({
        page:1,
        pageSize:10
    })
    
    const loadData=async ()=>{
        loading.value=true;
        try{
            let response;
            
            if (customApi) {
                // 使用自定义API，传递分页参数
                const requestParams = {
                    ...unref(initialParams),
                    [pageKey]: pageInfo.page,
                    [pageSizeKey]: pageInfo.pageSize
                };
                
                // 如果启用过滤空值，则移除空字符串、null、undefined 的参数
                let finalParams = requestParams;
                if (filterEmptyValues) {
                    finalParams = Object.fromEntries(
                        Object.entries(requestParams).filter(([_, value]) => {
                            return value !== '' && value !== null && value !== undefined;
                        })
                    );
                }
                
                response = await customApi(finalParams);
            } else {
                // 构建请求参数，支持自定义参数名
                let requestParams = {
                    ...unref(initialParams),
                    [pageKey]: pageInfo.page,
                    [pageSizeKey]: pageInfo.pageSize
                };
                
                // 如果启用过滤空值，则移除空字符串、null、undefined 的参数
                if (filterEmptyValues) {
                    requestParams = Object.fromEntries(
                        Object.entries(requestParams).filter(([_, value]) => {
                            return value !== '' && value !== null && value !== undefined;
                        })
                    );
                }
                
                response = await post(url, requestParams);
            }
            
            const {data} = response;
            dataList.value = data[listKey];
            totals.value = data[totalKey];
        }catch(error){
            console.log(error)
        } finally{
            loading.value=false
        } 
    }
    
    // 移除自动调用，让组件自己决定何时加载数据
    // onMounted(()=>{
    //     loadData()
    // })

    const handleSizeChange=(size:number)=>{
        pageInfo.pageSize=size;
        loadData()
    }
    const handleCurrentChange=(page:number)=>{
        pageInfo.page=page;
        loadData()
    }
    const resetPagination=()=>{
        pageInfo.page=1;
        pageInfo.pageSize=10;
        loadData()
    }
    return {
        dataList,
        loading,
        totals,
        pageInfo,
        loadData,
        handleSizeChange,
        handleCurrentChange,
        resetPagination
    }
}